using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;

namespace ScottCateAjax2008.Utilities
{
    public partial class ShowJavaScript : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["url"] != null)
            {
                if (!Page.IsPostBack)
                {
                    TextBox1.Text = HttpUtility.UrlDecode(Request.QueryString["url"].ToString());
                    if (TextBox1.Text.StartsWith("~"))
                    {
                        TextBox1.Text = string.Format("{0}://{2}:{1}{3}",
                                                      Request.Url.Scheme, 
                                                      Request.Url.Port,
                                                      Request.Url.Host, Page.ResolveUrl(TextBox1.Text));
                    }
                    FetchURL();
                }
            }

            string aspxPath = TextBox1.Text.Replace("aspx.js", "aspx");
            if (aspxPath.ToLower().EndsWith(".aspx"))
            {
                AspxFileLink.NavigateUrl = TextBox1.Text.Replace("aspx.js", "aspx");
                AspxFileLink.Text = Path.GetFileNameWithoutExtension(AspxFileLink.NavigateUrl);
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            FetchURL();
        }

        private void FetchURL()
        {
            string contents = string.Empty;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create((string) this.TextBox1.Text.Trim());
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
            {
                contents = HttpContext.Current.Server.HtmlEncode(sr.ReadToEnd());
                sr.Close();
            }
            string textarea = "<textarea name=\"code\" class=\"{0}\">{2}{2}{1}{2}{2}{2}</textarea>";
            contents = string.Format(textarea, "js", contents, Environment.NewLine);

            this.SourceCodePlaceHolder.Controls.Add(new LiteralControl(contents));
        }
    }
}